﻿using System;
using System.Collections.Generic;
using WAD.WEB.AppCode;
using WAD.DAL;
using WAD.Model;

namespace QD.Weijie.Web.WSite.ajax
{
    /// <summary>
    /// 代理商业务处理
    /// </summary>
    public class agent : PassportAjax
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "lockuser": this.LockUser(); break;
                case "getlist": this.GetList(); break;
                case "renewal": this.Renewal(); break;
            }
        }
        /// <summary>
        /// 禁用用户
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        void LockUser()
        {
            int state = Parse.Int("state", -1);
            int userid = Parse.Int("userid", 0);
            if (state < 0 || userid < 1)
                ParamError();
            if (DaoUser.UpdateState(userid, state))
                Success();
            else
                Fail();
        }

        [QD.Web.Ajax.AjaxMethod]
        void GetList()
        {
            int id = Parse.Int("id", 0);
            int page = Parse.Int("page", 1);
            string siteName = Parse.String("sitename");
            string username = Parse.String("username");

            string where = " agentid=" + UserId;
            if (!siteName.Equals(""))
                where += " and nick_name like '%" + QD.WX.Utill.Util.FilterSql(siteName) + "%'";
            if (!username.Equals(""))
                where += " and name='" + QD.WX.Utill.Util.FilterSql(username) + "'";
            PageData dt = DAO.GetListPage("[id],name,nick_name,qq,phone,state,date,version_id,end_date,'' as groupname", "id desc", page, 20, where, "[v_user_version]");
            for (int i = 0; i < dt.table.Rows.Count; i++)
            {
                if (dt.table.Rows[i]["version_id"] != DBNull.Value)
                    dt.table.Rows[i]["groupname"] = base.GetVersion(Convert.ToInt32(dt.table.Rows[i]["version_id"]));
            }
            JsonResult(0, "", dt);
        }

        /// <summary>
        /// 用户升级
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        void Renewal()
        {
            int id = Parse.Int("id", 0);
            int groupid = Parse.Int("gid", 0);
            int old_groupid = Parse.Int("old_gid", 0);
            int month = Parse.Int("month", 1);
            if (id < 1 || groupid < 1)
                ParamError();

            if (UserId < 1)
                JsonResult(-13, "请重新登录");

            //更新版本
            string msg = Renewal(id, UserId, groupid, month);   //升级
            if (!msg.Equals(""))
                JsonResult(-13, msg);
            JsonResult(0, "");
        }

        string Renewal(int userid, int agentid,  int groupid, int month)
        {
            Dictionary<string, object> version = GetVersions(groupid);
            if (version == null)
                return "版本错误,升级失败";

            Dictionary<string, object> model = DAO.Get("user", "id=" + userid, "agentid");
            if (model == null || model["agentid"] == DBNull.Value || Convert.ToInt32(model["agentid"]) != agentid)
                return "会员不存在或者不是您的客户,不允许升级";

            Dictionary<string, object> agentModel = GetAgent(agentid);
            if (agentModel == null)
                return "您不是代理商,不允许升级";
            //if (agentModel["version"] != null)
            //{
            //    string key = WeiJie.Web.AppCode.WJXConfig.AgentConfig.AGENT_GROUP;
            //    Dictionary<string, string> ver = (Dictionary<string, string>)agentModel["version"];
            //    if ((!ver.ContainsKey(key)) || string.IsNullOrEmpty(ver[key]))
            //        return "未开通微街秀代理功能，请联系客服";
            //}

            //代理商过期时间
            DateTime agent_date = Convert.ToDateTime(agentModel["endtime"]);

            if (agent_date < DateTime.Now)
                return "您的代理商账号已过期";

            Dictionary<string, object> userVersion = DAO.Get("user_version", "user_id=" + userid, "end_date");
            //折扣
            decimal discount = Convert.ToDecimal(agentModel["discount"]);
            //代理商余额
            Decimal balance = Convert.ToDecimal(agentModel["balance"]);

            //会员过期时间
            DateTime end_date = DateTime.Now.AddMonths(month);
            if (userVersion != null && userVersion["end_date"] != DBNull.Value)
                end_date = Convert.ToDateTime(userVersion["end_date"]).AddMonths(month);

            //最多可升级的年数
            int maxYears = Convert.ToInt32(agent_date.Subtract(Convert.ToDateTime(agentModel["addtime"])).TotalDays) / 365;
            if (maxYears < 1)
                maxYears = 1;
            if (end_date.Subtract(agent_date).TotalDays > 365)
                return string.Format("升级失败,代理的有效期为：{0}年,所以提单的客户有效期不能超过{0}年", maxYears);

            decimal price = (Convert.ToDecimal(version["price"]) * discount) / 100;   //折后价
            
            if (discount < 1 || discount > 99 || price < 0)
                price = 0;
            price = Math.Round(price);          //四舍五入
            
            decimal c_balance = balance - price;
            if (price > balance || c_balance < 0)
                return "余额不足,升级失败";
            
            bool isErr = false;
            int count1 = 0, count2 = 0, count3 = 0;
            try
            {
                //更新代理商余额
                if (price > 0)
                    count1 = UpdateAgentPrice(agentid, c_balance, Convert.ToInt32(agentModel["userid"]));

                //添加扣款记录              
                count2 = InsertDetail(userid, agentid, (price * -1), c_balance);

                //更新会员版本
                count3 = InsertVersion(userid, groupid, end_date);
            }
            catch { isErr = true; }

            //升级失败，回滚操作
            if (isErr)
            {
                if (count1 > 0)
                    UpdateAgentPrice(agentid, (c_balance + price));
                if (count2>0)

                return "升级失败，请刷新页面重试";
            }
            return "";
        }

        int InsertVersion(int user_id, int version_id, DateTime end_date)
        {
            //更新
            int count = DAO.ExecuteNonQuery(string.Format("update user_version set end_date='{0}',version_id={1} where user_id={2}", end_date, version_id, user_id));
            if (count < 1)
            {
                MUserVersion m = new MUserVersion();
                m.user_id = user_id;
                m.version_id = version_id;
                m.end_date = end_date;
                bool isadd = DaoUserVersion.Add(m);
                if (isadd) return 1;
            }
            return 0;
        }

        int InsertDetail(int userid, int agentid, decimal price, decimal banlance)
        {
            string sql = "insert into Agent_Record(agentid,amount,balance,direction,itemid,remarks,userip,addtime)values";
            sql += string.Format("({0},{1},{2},{3},{4},'{5}','{6}','{7}')", agentid, price, banlance, 2, userid, "微街秀客户升级，客户编号：" + userid.ToString(), Request.UserHostAddress, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
            sql += ";select @@IDENTITY";
            return Convert.ToInt32(DAO.ExecuteScalar(sql));
        }

        int UpdateAgentPrice(int agentid, Decimal price,int userid_sht=0)
        {
            return WAD.DAL.Union.DAOAgent.UpdateBalance(agentid, price, userid_sht);
        }

        Dictionary<string, object> GetVersions(int id)
        {
            return WAD.DAL.Union.DAOVersion.Get(id, "GroupSetting");
        }

        Dictionary<string, object> GetAgent(int id)
        {
            return WAD.DAL.Union.DAOAgent.Get(id);
        }


        /*注释 之前版本
        string Renewal_old(int userid, int agentid, int groupid, int month)
        {
            Dictionary<string, object> version = GetVersions(groupid);
            if (version == null)
                return "版本错误,升级失败";

            Dictionary<string, object> model = DAO.Get("user", "id=" + userid, "agentid");
            if (model == null || model["agentid"] == DBNull.Value || Convert.ToInt32(model["agentid"]) != agentid)
                return "会员不存在或者不是您的客户,不允许升级";

            Dictionary<string, object> agentModel = GetAgent(agentid);
            if (agentModel == null)
                return "您不是代理商,不允许升级";

            Dictionary<string, object> userVersion = DAO.Get("user_version", "user_id=" + userid, "end_date");
            //折扣
            int discount = Convert.ToInt32(agentModel["discount"]);
            //代理商余额
            Decimal balance = Convert.ToDecimal(agentModel["balance"]);
            //代理商过期时间
            DateTime agent_date = Convert.ToDateTime(agentModel["endtime"]);
            //会员过期时间
            DateTime end_date = DateTime.Now.AddMonths(month);
            if (userVersion != null && userVersion["end_date"] != DBNull.Value)
                end_date = Convert.ToDateTime(userVersion["end_date"]).AddMonths(month);

            //最多可升级的年数
            int maxYears = Convert.ToInt32(agent_date.Subtract(Convert.ToDateTime(agentModel["addtime"])).TotalDays) / 365;
            if (maxYears < 1)
                maxYears = 1;
            if (end_date.Subtract(agent_date).TotalDays > 365)
                return string.Format("升级失败,代理的有效期为：{0}年,所以提单的客户有效期不能超过{0}年", maxYears);

            Decimal price = (Convert.ToInt32(version["price"]) * discount) / 100;   //折后价
            if (discount < 1 || discount > 99 || price < 0)
                price = 0;

            decimal c_balance = balance - price;
            if (price > balance || c_balance < 0)
                return "余额不足,升级失败";


            bool isErr = false;
            int count1 = 0, count2 = 0, count3 = 0, count4 = 0;
            try
            {
                //更新代理商余额
                if (price > 0)
                    count1 = UpdateAgentPrice(agentid, c_balance);

                //添加扣款记录               
                count2 = InsertDetail(userid, agentid, price, balance);

                //更新会员版本
                count3 = InsertVersion(userid, groupid, end_date);
            }
            catch { isErr = true; }

            //升级失败，回滚操作
            if (isErr)
            {
                if (count1 > 0)
                    UpdateAgentPrice(agentid, (c_balance + price));
                return "升级失败，请刷新页面重试";
            }
            return "";
        }
        Dictionary<string, object> GetVersions_old(int id)
        {
            return DAOVersion.Get("version", "id=" + id);
        }
        Dictionary<string, object> GetAgent_old(int id)
        {
            return DAOVersion.Get("agent", "userid=" + id);
        }
        int UpdateAgentPrice_old(int agentid, Decimal price)
        {
            return DAO.ExecuteNonQuery(string.Format("update {0}.dbo.agent set balance={1} where userid={2}", DAO.DBName, price, agentid));
        }
        **/
    }
}